package com.ironone.streaming;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SlidingPaneLayout;
import android.util.Log;
import android.view.View;

import com.ironone.streaming.comm.NetworkCheck;
import com.ironone.streaming.comm.XMLParser;
import com.ironone.streaming.lite.R;
import com.ironone.streaming.model.NewsDataModel;

public class RssDataAsync extends AsyncTask<String, String, String> {

	List<NewsDataModel> newsList;
	Context con;
	FragmentActivity frag;
	SlidingPaneLayout mPane;

	public RssDataAsync(Context con) {
		this.con = con;
	}

	public RssDataAsync() {

	}

	public RssDataAsync(FragmentActivity frag) {
		this.frag = frag;
	}

	public RssDataAsync(FragmentActivity frag, SlidingPaneLayout mPane) {
		this.frag = frag;
		this.mPane = mPane;
	}

	public String getXmlFromUrl() {
		String xml = null;

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet("http://newsradio.lk/index.php?feed=rss2");
		try {
			HttpResponse response = httpclient.execute(httpget);
			if (response != null) {
				String line = "";
				InputStream inputstream = response.getEntity().getContent();
				line = convertStreamToString(inputstream);
				xml = line;
			} else {
				Log.e("getXmlFromUrl", "xml is null");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xml;
	}

	private String convertStreamToString(InputStream is) {
		String line = "";
		StringBuilder total = new StringBuilder();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		try {
			while ((line = rd.readLine()) != null) {
				total.append(line);
			}
		} catch (Exception e) {
		}
		return total.toString();
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		// Thread.setDefaultUncaughtExceptionHandler(new
		// ExceptionHandler(frag));
		/*
		 * try { Thread.setDefaultUncaughtExceptionHandler(new
		 * ExceptionHandler(frag)); } catch (Exception e) {
		 * Log.e("onPreExecute",e.toString()); }
		 */
		MainMenuFragment.progress_bar_layout.setVisibility(View.VISIBLE);
		MainMenuFragment.news_layout.setEnabled(false);

	}

	@Override
	protected String doInBackground(String... arg0) {
		Log.e(" Rss Async do in background", "executed 1st line");
		String xml = null;

		try {
			if ((NetworkCheck.isNetworkAvailable(frag))) {
				xml = getXmlFromUrl();
				// Testing
				// xml=null;
				// xml="this is a wrong format for xml";

				Log.e("Rss Async do in background", "executed 2nd line");
				String KEY_ITEM = "item";
				String KEY_TITLE = "title";
				String KEY_DESCRIPTION = "description";
				String KEY_LINK = "link";
				String KEY_CATEGORY = "category";

				XMLParser XMLParser = new XMLParser();
				Document doc = XMLParser.getDomElement(xml); // getting DOM
																// element

				org.w3c.dom.Element root = doc.getDocumentElement();
				NodeList nl = root.getElementsByTagName(KEY_ITEM);

				int size = nl.getLength();

				// MainMenuFragment.news_items = new NewsDataModel[size];
				newsList = new ArrayList<NewsDataModel>(size);

				for (int i = 0; i < nl.getLength(); i++) {
					org.w3c.dom.Element e = (org.w3c.dom.Element) nl.item(i);

					// Reading xml data inside <![CDATA[]]> tag: description
					NodeList description = e
							.getElementsByTagName(KEY_DESCRIPTION);
					org.w3c.dom.Element line = (org.w3c.dom.Element) description
							.item(0);
					String des = getCharacterDataFromElement(line);

					Log.e("description", des);

					boolean isEncoded = false;

					// Reading xml data inside <![CDATA[]]> tag: category
					NodeList category = e.getElementsByTagName(KEY_CATEGORY);
					org.w3c.dom.Element line1 = (org.w3c.dom.Element) category
							.item(0);
					String cat = getCharacterDataFromElement(line1);

					if (isSinhala(cat)) {
						isEncoded = true;
					}

					newsList.add(new NewsDataModel(XMLParser.getValue(e,
							KEY_TITLE), des, XMLParser.getValue(e, KEY_LINK),
							isEncoded));

					// loading web images

					if (isImageUrlPresent(des)) {
						String image_url = pullImageLink(des);
						Log.e("image link", image_url);
						newsList.get(i).setImage(getImagefromLink(image_url));
					} else {
						Log.e("image url", "absent");
					}
				}

				// FormObject.getInstance().setNewsData(newsList);
				MainMenuFragment.newsList = newsList;
				Log.e("Rss Async do in background", "last line");
			} else {

				Log.e("Rss Async no network", "no net");
				newsList = new ArrayList<NewsDataModel>(1);
				newsList.add(new NewsDataModel("No news",
						"Please retry in few seconds", "http://newsradio.lk/",
						false));
				MainMenuFragment.newsList = newsList;
				// MainMenuFragment.newsList = null;
			}

		} catch (Exception e) {
			Log.e("Rss Async do in background exception", e.toString());
			newsList = new ArrayList<NewsDataModel>(1);
			newsList.add(new NewsDataModel("No news",
					"Please retry in few seconds", "http://newsradio.lk/",
					false));
			MainMenuFragment.newsList = newsList;
			// MainMenuFragment.newsList = null;
		}
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		MainMenuFragment.progress_bar_layout.setVisibility(View.INVISIBLE);
		MainMenuFragment.news_layout.setEnabled(true);

		Log.e("On post", "1st line executed");

		if (mPane.isOpen() && MainMenuFragment.isNewsSelected) {
			Log.e("On post", "if");
			frag.getSupportFragmentManager().beginTransaction()
					.replace(R.id.pane2, new NewsFragment(), "pane2").commit();
			mPane.closePane();
		}
		Log.e("On post", "News fragment loaded");

	}

	// Reading xml data inside <![CDATA[]]> tag
	public static String getCharacterDataFromElement(org.w3c.dom.Element e) {
		Node child = e.getFirstChild();
		if (child instanceof CharacterData) {
			CharacterData cd = (CharacterData) child;
			return cd.getData();
		}
		return "";
	}

	// Check for sinhala unicode strings
	public boolean isSinhala(String s) {
		boolean value = false;
		for (int i = 0; i < Character.codePointCount(s, 0, s.length()); i++) {
			int c = s.codePointAt(i);
			if (c >= 0x0D80 && c <= 0x0DFF) {
				value = true;
				break;
			}
		}
		return value;
	}

	// Extracting image url from the description in xml
	public String pullImageLink(String text) {
		String link = "";
		String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&amp;@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#/%=~_()|]";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(text);
		while (m.find()) {
			String urlStr = m.group();
			if (urlStr.startsWith("(") && urlStr.endsWith(")")) {
				urlStr = urlStr.substring(1, urlStr.length() - 1);
			}
			link = urlStr;
		}
		return link;
	}

	public boolean isImageUrlPresent(String text) {
		if (text.contains("http://")) {
			return true;
		} else {
			return false;
		}
	}

	// Loading image from web
	public Bitmap getImagefromLink(String image_url) {
		URL my_url = null;
		try {
			my_url = new URL(image_url);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Bitmap bmp = null;
		try {
			bmp = BitmapFactory.decodeStream(my_url.openConnection()
					.getInputStream());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return bmp;
	}
}